
package com.shop.cloud.weixin.admin.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cloud.common.core.constant.CacheConstants;
import com.shop.cloud.weixin.admin.config.open.WxOpenConfiguration;
import com.shop.cloud.weixin.admin.mapper.WxUserMapper;
import com.shop.cloud.weixin.admin.service.WxMaNicknameAuditService;
import com.shop.cloud.weixin.common.constant.WxConstant;
import com.shop.cloud.weixin.common.constant.WxReturnCode;
import com.shop.cloud.weixin.common.dto.WxAppSetNickNameDTO;
import com.shop.cloud.weixin.common.entity.WxApp;
import com.shop.cloud.weixin.admin.mapper.WxAppMapper;
import com.shop.cloud.weixin.admin.service.WxAppService;
import com.shop.cloud.weixin.common.entity.WxMaNicknameAudit;
import com.shop.cloud.weixin.common.entity.WxUser;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.open.bean.auth.WxOpenAuthorizerInfo;
import me.chanjar.weixin.open.bean.result.*;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * 微信应用
 *
 * @author
 * @date 2019-03-15 10:26:44
 */
@Service
@AllArgsConstructor
public class WxAppServiceImpl extends ServiceImpl<WxAppMapper, WxApp> implements WxAppService {

	private final WxUserMapper wxUserMapper;
	private final WxMaNicknameAuditService wxMaNicknameAuditService;

	/**
	 * 微信原始标识查找
	 * @param weixinSign
	 * @return
	 */
	@Override
	@Cacheable(value = CacheConstants.WXAPP_WEIXIN_SIGN_CACHE, key = "#weixinSign")
	public WxApp findByWeixinSign(String weixinSign){
		WxApp wxApp = null;
		List<WxApp> listWxApp = baseMapper.findByWeixinSign(weixinSign);
		if(CollectionUtil.isNotEmpty(listWxApp)){
			wxApp = listWxApp.get(0);
		}
		return wxApp;
	}

	@Override
	@Cacheable(value = CacheConstants.WXAPP_APP_ID_CACHE, key = "#appId")
	public WxApp findByAppId(String appId) {
		WxApp wxApp = null;
		List<WxApp> listWxApp = baseMapper.findByAppId(appId);
		if(CollectionUtil.isNotEmpty(listWxApp)){
			wxApp = listWxApp.get(0);
		}
		return wxApp;
	}

	@Override
	public void setNickName(WxAppSetNickNameDTO wxAppSetNickNameDTO) {
		WxFastMaSetNickameResult wxFastMaSetNickameResult;
		try {
			//调用微信服务修改
			wxFastMaSetNickameResult = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxMaServiceByAppid(wxAppSetNickNameDTO.getAppId()).getBasicService().setNickname(
				wxAppSetNickNameDTO.getNickname(),
				wxAppSetNickNameDTO.getIdCard(),
				wxAppSetNickNameDTO.getLicense(),
				wxAppSetNickNameDTO.getNamingOtherStuff1(),
				wxAppSetNickNameDTO.getNamingOtherStuff2()
			);
			if(!WxReturnCode.SUC_0.getCode().equals(wxFastMaSetNickameResult.getErrcode())){
				throw new RuntimeException(wxFastMaSetNickameResult.getErrmsg());
			}
			if(wxFastMaSetNickameResult.getAuditId() != null){
				//需审核，保存审核记录
				WxMaNicknameAudit wxMaNicknameAudit = new WxMaNicknameAudit();
				wxMaNicknameAudit.setAppId(wxAppSetNickNameDTO.getAppId());
				wxMaNicknameAudit.setAuditId(String.valueOf(wxFastMaSetNickameResult.getAuditId()));
				wxMaNicknameAudit.setNickname(wxAppSetNickNameDTO.getNickname());
				wxMaNicknameAuditService.save(wxMaNicknameAudit);
				wxMaNicknameAuditService.queryNicknameAudit(wxMaNicknameAudit.getId());
			}else{
				//未返回audit_id，说明名称已直接设置成功，无需审核，更新本地数据
				WxApp wxApp2 = new WxApp();
				wxApp2.setId(wxAppSetNickNameDTO.getAppId());
				wxApp2.setName(wxAppSetNickNameDTO.getNickname());
				baseMapper.updateById(wxApp2);
				WxMaNicknameAudit wxMaNicknameAudit = new WxMaNicknameAudit();
				wxMaNicknameAudit.setAppId(wxAppSetNickNameDTO.getAppId());
				wxMaNicknameAudit.setRet(WxConstant.WX_NICKNAME_AUDIT_RET_3);
				wxMaNicknameAudit.setNickname(wxAppSetNickNameDTO.getNickname());
				wxMaNicknameAuditService.save(wxMaNicknameAudit);
			}
		} catch (WxErrorException e) {
			e.printStackTrace();
			Integer errorCode = e.getError().getErrorCode();
			throw new RuntimeException(WxReturnCode.getMsg("ERR_"+errorCode, e));
		}
	}

	@Override
	public void setSignature(WxApp wxApp) {
		WxOpenResult wxOpenResult;
		try {
			//调用微信服务修改
			wxOpenResult = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxMaServiceByAppid(wxApp.getId()).getBasicService().modifySignature(wxApp.getSignature());
			if(!WxReturnCode.SUC_0.getCode().equals(wxOpenResult.getErrcode())){
				throw new RuntimeException(wxOpenResult.getErrmsg());
			}
			//修改本地数据
			WxApp wxApp2 = new WxApp();
			wxApp2.setId(wxApp.getId());
			wxApp2.setSignature(wxApp.getSignature());
			baseMapper.updateById(wxApp2);
		} catch (WxErrorException e) {
			e.printStackTrace();
			Integer errorCode = e.getError().getErrorCode();
			throw new RuntimeException(WxReturnCode.getMsg("ERR_"+errorCode, e));
		}
	}

	@Override
	public void setLogo(WxApp wxApp) {
		WxOpenResult wxOpenResult;
		String logo;
		String qrcodeUrl;
		try {
			//调用微信服务修改，wxApp.getLogo()要传入media_id
			wxOpenResult = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxMaServiceByAppid(wxApp.getId()).getBasicService().modifyHeadImage(wxApp.getLogo(), 0, 0, 1, 1);
			//修改成功，重新获取头像URL、小程序码Url
			WxOpenAuthorizerInfoResult wxOpenAuthorizerInfoResult = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getAuthorizerInfo(wxApp.getId());
			WxOpenAuthorizerInfo wxOpenAuthorizerInfo = wxOpenAuthorizerInfoResult.getAuthorizerInfo();
			qrcodeUrl = wxOpenAuthorizerInfo.getQrcodeUrl();
			logo = wxOpenAuthorizerInfo.getHeadImg();
			if(!WxReturnCode.SUC_0.getCode().equals(wxOpenResult.getErrcode())){
				throw new RuntimeException(wxOpenResult.getErrmsg());
			}
			//修改本地数据
			WxApp wxApp2 = new WxApp();
			wxApp2.setId(wxApp.getId());
			wxApp2.setLogo(logo);
			wxApp2.setQrCode(qrcodeUrl);
			baseMapper.updateById(wxApp2);
		} catch (WxErrorException e) {
			e.printStackTrace();
			Integer errorCode = e.getError().getErrorCode();
			throw new RuntimeException(WxReturnCode.getMsg("ERR_"+errorCode, e));
		}
	}

	@Override
	@Cacheable(value = CacheConstants.WXAPP_APP_ID_CACHE, key = "#id")
	public WxApp getById(Serializable id) {
		return baseMapper.selectById(id);
	}

	@Override
	@Caching(evict={
			@CacheEvict(value = CacheConstants.WXAPP_WEIXIN_SIGN_CACHE, allEntries = true),
			@CacheEvict(value = CacheConstants.WXAPP_APP_ID_CACHE, allEntries = true)
	})
	public boolean updateById(WxApp entity) {
		baseMapper.updateById(entity);
		return Boolean.TRUE;
	}

	@Override
	@Caching(evict={
			@CacheEvict(value = CacheConstants.WXAPP_WEIXIN_SIGN_CACHE, allEntries = true),
			@CacheEvict(value = CacheConstants.WXAPP_APP_ID_CACHE, allEntries = true)
	})
	public boolean removeById(Serializable id) {
		baseMapper.deleteById(id);
		//删除该appId下的微信用户
		if(id != null){
			wxUserMapper.delete(Wrappers.<WxUser>lambdaQuery()
					.eq(WxUser::getAppId, id));
		}
		return Boolean.TRUE;
	}
}
